import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:dio/dio.dart';
import 'news_modle_entity.dart';
import 'widgets/news_item.dart';
import 'dart:io';
import 'dart:async';
import 'package:path_provider/path_provider.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  Dio dio = Dio();


  Future<File> _getLocalFile() async {
    // 获取应用目录
    String dir = (await getExternalStorageDirectories(type: StorageDirectory.downloads))!.first.path;
    return File('$dir/data.json');
  }

  Future<String> _readCounter() async {
    try {
      File file = await _getLocalFile();
      // 读取点击次数（以字符串）
      String contents = await file.readAsString();
      return contents;
    } on FileSystemException {
      return "";
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: FutureBuilder(
          future: _readCounter(),
          builder: (BuildContext context, AsyncSnapshot snapshot){
            if(snapshot.connectionState == ConnectionState.done){
              if(snapshot.hasError){
                return const Text("请求失败");
              }else{
                var resJson = snapshot.data.toString();
                var newsEntry = NewsModleEntity.fromJson(json.decode(resJson));
                return ListView.builder(
                    itemCount: newsEntry.result.data.length,
                    itemBuilder: (BuildContext context, int index){
                      return NewsItem(newsData: newsEntry.result.data[index]);
                    }
                );
              }
            }else{
              return const Text("请求中");
            }
          },
        )
      )
    );
  }
}
